package br.com.simora.musica;

import java.util.List;

import javax.inject.Named;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import br.com.simora.persistence.AbstractDAO;

@Named("musicaDAO")
public class MusicaDAO extends AbstractDAO {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5329463490228891776L;

	public Musica recuperaMusicaPorNomeEArtista(String nome, Artista artista){
		CriteriaBuilder qb = manager.getCriteriaBuilder();
		CriteriaQuery<Musica> cq = qb.createQuery(Musica.class);
		Root<Musica> tb = cq.from(Musica.class);
		cq.select(tb);
		cq.where(qb.equal(tb.get("nome"), nome), qb.equal(tb.get("artista"), artista));
		return (Musica) recuperaRegistro(montaQuery(cq));
	}

	public List<Musica> recuperaMusicaPorNomeEArtistaLike(String query, String idArtista) {
		CriteriaBuilder qb = manager.getCriteriaBuilder();
		CriteriaQuery<Musica> cq = qb.createQuery(Musica.class);
		Root<Musica> tb = cq.from(Musica.class);
		
		Predicate l2 = null; 
		if(null != idArtista && !"".equals(idArtista)){
			Artista artista = manager.find(Artista.class, Integer.parseInt(idArtista));
			l2 = qb.equal(tb.get("artista"), artista);
		}
		Expression<String> path = tb.get("nome");
		//Expression<String> param = qb.parameter(String.class);
		Predicate l1 = qb.like(path, query+"%");
		cq.select(tb);
		if(l2 != null){
			cq.where(l1, l2);
		} else {
			cq.where(l1);
		}
		return (List<Musica>) recuperaLista(montaQuery(cq));
	}
	
}